<template>
  <div class="notification-bell">
    <!-- 消息铃铛按钮 -->
    <el-popover
      ref="popoverRef"
      :visible="showNotificationPanel"
      placement="bottom-end"
      :width="380"
      trigger="click"
      popper-class="notification-popover"
      @show="handlePopoverShow"
      @hide="handlePopoverHide"
    >
      <template #reference>
        <el-button
          class="bell-button"
          :class="{ 'has-unread': totalUnreadCount > 0 }"
          circle
          size="large"
          @click="toggleNotificationPanel"
        >
          <el-badge
            :value="totalUnreadCount"
            :max="99"
            :hidden="totalUnreadCount === 0"
            type="danger"
          >
            <el-icon :size="20">
              <Bell />
            </el-icon>
          </el-badge>
        </el-button>
      </template>

      <!-- 通知面板内容 -->
      <div class="notification-panel">
        <!-- 面板头部 -->
        <div class="panel-header">
          <div class="header-left">
            <h3 class="panel-title">消息通知</h3>
            <span v-if="totalUnreadCount > 0" class="unread-count">
              {{ totalUnreadCount }}条未读
            </span>
          </div>
          <div class="header-right">
            <el-button
              v-if="totalUnreadCount > 0"
              size="small"
              type="primary"
              text
              @click="markAllAsRead"
            >
              全部已读
            </el-button>
            <el-button
              size="small"
              type="primary"
              text
              @click="clearAllNotifications"
            >
              清空
            </el-button>
          </div>
        </div>

        <!-- 通知列表 -->
        <div class="notification-list">
          <el-scrollbar max-height="400px">
            <!-- 空状态 -->
            <div v-if="notifications.length === 0" class="empty-state">
              <el-icon :size="48" class="empty-icon">
                <ChatDotRound />
              </el-icon>
              <p class="empty-text">暂无消息通知</p>
            </div>

            <!-- 通知项列表 -->
            <div
              v-for="notification in notifications"
              :key="notification.id"
              class="notification-item"
              :class="{ 'unread': !notification.isRead }"
              @click="handleNotificationClick(notification)"
            >
              <!-- 团队头像 -->
              <div class="notification-avatar">
                <el-avatar :size="40" :src="notification.teamAvatar">
                  {{ notification.teamName?.charAt(0) }}
                </el-avatar>
              </div>

              <!-- 通知内容 -->
              <div class="notification-content">
                <div class="content-header">
                  <span class="team-name">{{ notification.teamName }}</span>
                  <span class="sender-name">{{ notification.senderName }}</span>
                  <span class="time">{{ formatTime(notification.timestamp) }}</span>
                </div>
                
                <div class="content-body">
                  <div class="message-preview">
                    <el-icon v-if="notification.messageType === 'image'" class="message-icon">
                      <Picture />
                    </el-icon>
                    <el-icon v-else-if="notification.messageType === 'file'" class="message-icon">
                      <Document />
                    </el-icon>
                    <span class="message-text">{{ getMessagePreview(notification) }}</span>
                  </div>
                  
                  <div v-if="notification.unreadCount > 1" class="unread-badge">
                    {{ notification.unreadCount }}条未读
                  </div>
                </div>
              </div>

              <!-- 未读指示器 -->
              <div v-if="!notification.isRead" class="unread-indicator"></div>
            </div>
          </el-scrollbar>
        </div>

        <!-- 面板底部 -->
        <div class="panel-footer">
          <el-button
            type="primary"
            text
            size="small"
            @click="goToTeamList"
          >
            查看所有团队
          </el-button>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Bell,
  ChatDotRound,
  Picture,
  Document
} from '@element-plus/icons-vue'
import { useTeamChatStore } from '@/stores/teamChat'
import { useNotificationStore } from '@/stores/notification'

// 通知数据类型
interface NotificationItem {
  id: string
  teamId: number
  teamName: string
  teamAvatar?: string
  senderId: number
  senderName: string
  messageType: 'text' | 'image' | 'file'
  content: string
  fileName?: string
  timestamp: number
  isRead: boolean
  unreadCount: number
}

// 组合函数
const router = useRouter()
const teamChatStore = useTeamChatStore()
const notificationStore = useNotificationStore()

// 响应式数据
const popoverRef = ref()
const showNotificationPanel = ref(false)

// 计算属性
const notifications = computed(() => notificationStore.notifications)
const totalUnreadCount = computed(() => notificationStore.totalUnreadCount)

// 方法
const toggleNotificationPanel = () => {
  showNotificationPanel.value = !showNotificationPanel.value
}

const handlePopoverShow = () => {
  showNotificationPanel.value = true
  // 标记通知为已查看（但不是已读）
  notificationStore.markAsViewed()
}

const handlePopoverHide = () => {
  showNotificationPanel.value = false
}

const handleNotificationClick = (notification: NotificationItem) => {
  // 标记单个通知为已读
  notificationStore.markAsRead(notification.id)
  
  // 跳转到对应的团队聊天室
  router.push({
    name: 'TeamDetail',
    params: { id: notification.teamId.toString() },
    query: { tab: 'chat' }
  })
  
  // 关闭通知面板
  showNotificationPanel.value = false
}

const markAllAsRead = () => {
  notificationStore.markAllAsRead()
  ElMessage.success('所有消息已标记为已读')
}

const clearAllNotifications = () => {
  notificationStore.clearAll()
  ElMessage.success('所有通知已清空')
}

const goToTeamList = () => {
  router.push({ name: 'TeamList' })
  showNotificationPanel.value = false
}

const getMessagePreview = (notification: NotificationItem) => {
  switch (notification.messageType) {
    case 'image':
      return '[图片]'
    case 'file':
      // 优先使用解密后的文件名
      const fileName = notification.decryptedFileName || notification.fileName || '未知文件'
      return `[文件] ${fileName}`
    default:
      // 优先使用解密后的内容
      const content = notification.decryptedContent || notification.content
      return content.length > 30
        ? content.substring(0, 30) + '...'
        : content
  }
}

const formatTime = (timestamp: number) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  // 小于1分钟显示"刚刚"
  if (diff < 60000) {
    return '刚刚'
  }
  
  // 小于1小时显示分钟
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  
  // 小于24小时显示小时
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  }
  
  // 今天显示时间
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }
  
  // 昨天
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return `昨天 ${date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })}`
  }
  
  // 其他显示日期
  return date.toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit'
  })
}

// 生命周期
onMounted(() => {
  // 初始化通知系统
  notificationStore.init()
})

onUnmounted(() => {
  // 清理资源
  notificationStore.cleanup()
})
</script>

<style scoped lang="scss">
.notification-bell {
  position: relative;
}

.bell-button {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
  color: var(--el-text-color-regular);
  transition: all 0.3s;

  &:hover {
    background: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary-light-7);
    color: var(--el-color-primary);
  }

  &.has-unread {
    background: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary-light-7);
    color: var(--el-color-primary);
    
    .el-icon {
      animation: bellShake 2s infinite;
    }
  }
}

.notification-panel {
  padding: 0;
  
  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    background: var(--el-bg-color-page);

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      .panel-title {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .unread-count {
        font-size: 12px;
        color: var(--el-color-primary);
        background: var(--el-color-primary-light-9);
        padding: 2px 8px;
        border-radius: 10px;
      }
    }

    .header-right {
      display: flex;
      gap: 8px;
    }
  }

  .notification-list {
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 40px 20px;
      color: var(--el-text-color-secondary);

      .empty-icon {
        margin-bottom: 12px;
        color: var(--el-text-color-disabled);
      }

      .empty-text {
        margin: 0;
        font-size: 14px;
      }
    }

    .notification-item {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      padding: 16px 20px;
      cursor: pointer;
      transition: background-color 0.2s;
      position: relative;

      &:hover {
        background: var(--el-fill-color-light);
      }

      &.unread {
        background: var(--el-color-primary-light-9);
        
        &:hover {
          background: var(--el-color-primary-light-8);
        }
      }

      .notification-avatar {
        flex-shrink: 0;
      }

      .notification-content {
        flex: 1;
        min-width: 0;

        .content-header {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 4px;

          .team-name {
            font-weight: 600;
            color: var(--el-color-primary);
            font-size: 14px;
          }

          .sender-name {
            color: var(--el-text-color-regular);
            font-size: 13px;
          }

          .time {
            color: var(--el-text-color-secondary);
            font-size: 12px;
            margin-left: auto;
          }
        }

        .content-body {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .message-preview {
            display: flex;
            align-items: center;
            gap: 4px;
            flex: 1;
            min-width: 0;

            .message-icon {
              font-size: 14px;
              color: var(--el-text-color-secondary);
            }

            .message-text {
              color: var(--el-text-color-regular);
              font-size: 13px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }

          .unread-badge {
            font-size: 12px;
            color: var(--el-color-primary);
            background: var(--el-color-primary-light-9);
            padding: 2px 6px;
            border-radius: 8px;
            white-space: nowrap;
          }
        }
      }

      .unread-indicator {
        position: absolute;
        right: 8px;
        top: 50%;
        transform: translateY(-50%);
        width: 8px;
        height: 8px;
        background: var(--el-color-primary);
        border-radius: 50%;
      }
    }
  }

  .panel-footer {
    padding: 12px 20px;
    border-top: 1px solid var(--el-border-color-lighter);
    background: var(--el-bg-color-page);
    text-align: center;
  }
}

@keyframes bellShake {
  0%, 50%, 100% { transform: rotate(0deg); }
  10%, 30% { transform: rotate(-10deg); }
  20%, 40% { transform: rotate(10deg); }
}

// 响应式设计
@media (max-width: 768px) {
  .notification-panel {
    width: 320px !important;
    
    .panel-header {
      padding: 12px 16px;
      
      .panel-title {
        font-size: 14px;
      }
    }

    .notification-item {
      padding: 12px 16px;
      
      .notification-avatar {
        .el-avatar {
          --el-avatar-size: 32px;
        }
      }
    }
  }
}
</style>

<style lang="scss">
.notification-popover {
  padding: 0 !important;
  
  .el-popover__arrow {
    display: none;
  }
}
</style>
